/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.railway.utils;

import java.io.IOException;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

public class RestServer {

    private static String serverurl = "http://localhost";
    private static String apipath = "/RailwayWeb/api/";
    private static final int connectionTimeout = 3000;
    private static final int socketTimeout = 5000;
    private static RequestConfig config = RequestConfig.custom()
            .setConnectTimeout(connectionTimeout)
            .setSocketTimeout(socketTimeout)
            .build();

    public static void setServerurl(String serverurl) {
        RestServer.serverurl = serverurl;
    }

    public static String getServerUrl() {
        return serverurl;
    }

    public static String getApipath() {
        return apipath;
    }

    public static String httpPost(String action, Map<String, Object> data) {
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost post = new HttpPost(getServerUrl() + getApipath() + action);
            post.setConfig(config);
            post.setHeader("content-type", "application/json");
            JSONObject json = new JSONObject();
            for (Map.Entry<String, Object> entry : data.entrySet()) {
                json.put(entry.getKey(), entry.getValue());
            }
            StringEntity entity = new StringEntity(json.toString());
            post.setEntity(entity);
            HttpResponse respond = httpClient.execute(post);
            int statuscode = respond.getStatusLine().getStatusCode();
            String result = EntityUtils.toString(respond.getEntity());
            if (result.equals("")) {
                result = "\"\"";
            }
            return "{\"status\":" + statuscode + ", \"content\": " + result + "}";
        } catch (JSONException ex) {
            return "{\"error\": true, \"message\":\"Unable to insert data. Please try again later.\"}";
        } catch (IOException ex) {
            return "{\"error\": true, \"message\":\"Connection error. Please try again later\"}";
        } catch (ParseException ex) {
            return "{\"error\": true, \"message\":\"Unable to parse data.\"}";
        }
    }

    public static String httpGet(String action, String id) {
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpGet get = new HttpGet(getServerUrl() + getApipath() + action
                    + (id.equals("") ? id : "/" + id));
            get.setConfig(config);
            HttpResponse respond = httpClient.execute(get);
            int statuscode = respond.getStatusLine().getStatusCode();
            String result = EntityUtils.toString(respond.getEntity());
            if (result.equals("")) {
                result = "\"Not found\"";
            }
            return "{\"status\":" + statuscode + ", \"content\": " + result + "}";
        } catch (IOException ex) {
            return "{\"error\": true, \"message\":\"Connection error. Please try again later\"}";
        } catch (ParseException ex) {
            return "{\"error\": true, \"message\":\"Unable to parse data.\"}";
        }
    }

    public static String httpPut(String action, Map<String, Object> data,
            String id) {
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPut put = new HttpPut(getServerUrl() + getApipath() + action
                    + "/" + id);
            put.setConfig(config);
            put.setHeader("content-type", "application/json");
            if (!data.isEmpty()) {
                JSONObject json = new JSONObject();
                for (Map.Entry<String, Object> entry : data.entrySet()) {
                    json.put(entry.getKey(), entry.getValue());
                }
                StringEntity entity = new StringEntity(json.toString());
                put.setEntity(entity);
            }
            HttpResponse respond = httpClient.execute(put);
            int statuscode = respond.getStatusLine().getStatusCode();
            String result = EntityUtils.toString(respond.getEntity());
            if (result.equals("")) {
                result = "\"Not found\"";
            }
            return "{\"status\":" + statuscode + ", \"content\": " + result + "}";
        } catch (JSONException ex) {
            return "{\"error\": true, \"message\":\"Unable to update. Please try again later.\"}";
        } catch (IOException ex) {
            return "{\"error\": true, \"message\":\"Connection error. Please try again later\"}";
        } catch (ParseException ex) {
            return "{\"error\": true, \"message\":\"Unable to parse data.\"}";
        }
    }

    public static String httpDelete(String action, String id) {
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpDelete delete = new HttpDelete(getServerUrl() + getApipath() + action + "/" + id);
            delete.setConfig(config);
            delete.setHeader("content-type", "application/json");
            HttpResponse respond = httpClient.execute(delete);
            int statuscode = respond.getStatusLine().getStatusCode();
            String result = EntityUtils.toString(respond.getEntity());
            if (result.equals("")) {
                result = "\"Not found\"";
            }
            return "{\"status\":" + statuscode + ", \"content\": " + result + "}";
        } catch (IOException ex) {
            return "{\"error\": true, \"message\":\"Connection error. Please try again later\"}";
        } catch (ParseException ex) {
            return "{\"error\": true, \"message\":\"Unable to parse data.\"}";
        }
    }
}
